<template>
  <div class="edit-department">
    <a-modal
      width="1000px"
      :title="updateTitles"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="spinning" tip="正在加载数据中...">
        <a-form :form="form" @submit="handleSubmit">
          <a-row :gutter="10">
          <a-col :span="12">
            <a-form-item label="您的姓名" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
              <a-input
                v-decorator="[
                  'MC',
                  {
                    rules: [{ required: true, message: '请输入您的姓名!' }],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="您的电话" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
              <a-input
                v-decorator="[
                  'Phone',
                  {
                    rules: [
                      { required: false, message: '请输入您的电话!', whitespace: true, trigger: 'change' },
                      { validator: validatePhone },
                    ],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="您的地址" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
              <a-input
                v-decorator="[
                  'DZ',
                  {
                    rules: [{ required: true, message: '请输入您的地址!' }],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务时间" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
              <a-range-picker
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :value="timevalue"
                :placeholder="['开始时间', '结束时间']"
                @change="onChange"
                @ok="onOk"
              >
                <template slot="renderExtraFooter"> extra footer </template>
              </a-range-picker>
            </a-form-item></a-col
          >
          <a-col :span="12">
            <a-form-item label="服务项目" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
              <a-input
                v-decorator="[
                  'NAME',
                  {
                    rules: [{ required: true, message: '请输入服务项目!' }],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="其他服务" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
              <a-input v-decorator="['MS']" />
            </a-form-item>
          </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import { setDepartments, getDepartmentSelect } from '@/api/system'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getFWLBDrptApi, postAddNewsApi, getCsglListApi, postupdateFWFBApi } from '@/api/service'
import { validFixedTelphone, validTelphone } from '@/utils/validate'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    propsData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      confirmLoading: false,
      treeName: '',
      headers: {
        Authorization: storage.get(ACCESS_TOKEN),
        GF: this.$store.getters.userid,
      },
      dateString: [],
      timevalue:[],
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      parentTreeList: [
        {
          NAME: '无',
          ID: 0,
          children: [],
        },
      ],
      levelList: [],
      hoturl: '',
      iconurl: '',
      FWLBTBparameter: [],
      form: this.$form.createForm(this, { name: 'department' }),
    }
  },
  watch: {
    propsData: function () {
      this.fetchDepartment()
    },
  },
  computed: {
    // levelList:treeNameLookup(),
    updateTitles: function () {
      const {
        propsData: { type },
      } = this
      if (type === 'add') {
        return '新增服务'
      } else if (type === 'addChild') {
        return '新增子服务'
      } else {
        return '修改服务'
      }
    },
  },
  methods: {
    onChange(value, dateString) {
      this.timevalue = value;
      // this.dateString = dateString[0] + ' 到 ' + dateString[1]
      this.dateString = dateString
    },
    onOk(value) {
      console.log('onOk: ', value)
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
      }
      if (!validTelphone(value)) {
        callback(new Error('联系电话输入有误，请重新输入'))
      }
      callback()
    },
    fetchDepartment() {
      this.spinning = true
      const {
        propsData: { type, record },
        form: { setFieldsValue },
      } = this
      console.log('的split()',record.StartSJ.split('到'));
      this.timevalue = record.StartSJ.split('到')
      console.log('this.timevalue',this.timevalue);
      const tree = new Promise((resolve, reject) => {
        getFWLBDrptApi({
          type: 'ddepartemnt',
          Contype: this.$store.getters.loginName,
        }).then((res) => {
          resolve(res.data)
        })
      })
      const category = new Promise((resolve, reject) => {
        getFWLBDrptApi().then((res) => {
          resolve(res.data)
        })
      })
      getCsglListApi({
        ClassKey: 'FWLBTB',
      }).then((res) => {
        this.FWLBTBparameter = res.data
      })
      Promise.all([tree, category])
        .then((res) => {
          this.parentTreeList[0].children = res[0]
          console.log(this.parentTreeList)
          this.levelList = res[1]
          if (type === 'addChild') {
            setFieldsValue({ Fid: record.ID })
          }
          if (type === 'add' || type === 'addChild') return
          record.BBDJ = record.BBDJ ? Number(record.BBDJ) : undefined
          this.$nextTick(() => {
            setFieldsValue(pick(record, ['MC', 'Phone', 'DZ', 'StartSJ', 'NAME', 'MS', 'DepartmentHead', 'FZRDH']))
          })
        })
        .catch(() => {
          this.$message.error('网络请求失败, 请稍后重试')
        })
        .finally(() => {
          this.spinning = false
        })
    },
    handleSubmit() {
      const {
        form: { validateFields },
        propsData: { type, record },
        $message,
      } = this
      validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          const submitData = Object.assign({}, values, {})
          if (type === 'update') {
            submitData.ID = record.ID
            this.dateString = this.dateString[0] + ' 到 ' + this.dateString[1]

            postupdateFWFBApi(
              Object.assign({}, values, {
                ID: record.ID,
                StartSJ: this.dateString,
              })
            )
              .then((res) => {
                if (res.code === 200) {
                  $message.success(res.message || '提交成功', 3)
                  this.handleCancel()
                  this.$parent.$parent.$refs.table.refresh(true)
                } else {
                  $message.error(res.message || '提交失败', 3)
                }
              })
              .catch((err) => {
                $message.error(err, 3)
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.$emit('update:visible', false)
    },
  },
}
</script>
